#!/usr/bin/env python
# -*- coding:utf8 -*-
'''
Created on 2016年5月5日
@author: zhaoxiang
'''
import sys

#----------------------------------------------------------
# @function: 二分查找索引id值的对应内容
#----------------------------------------------------------
def search2(geoBlockList,ipID):
    low = 0
    high = len(geoBlockList) - 1
    while(low <= high): 
        mid = (low + high)/2 
        midval = geoBlockList[mid] 
        if midval[1] < ipID: 
            low = mid + 1  
        elif midval[0] > ipID: 
            high = mid - 1  
        else: 
            return midval[2]
    return None

#----------------------------------------------------------
# @out: (1)资源GeoLiteCity-Blocks 
#       (2)资源GeoLiteCity-Location
# @function: 读取资源
#----------------------------------------------------------
def load():
    geoBlockList = []
    #文件已排序
    filename = "/usr/local/cloud/hive/lib/py/udf/ipforcity/GeoLiteCity-Blocks.csv"
    for line in open(filename,"r"):
        spu = line.strip().split(",")
        geoBlockList.append((int(spu[0]),int(spu[1]),int(spu[2])))
    checktable = {}
    filename = "/usr/local/cloud/hive/lib/py/udf/ipforcity/final.txt"
#     filename = "/home/xinran/xinran/log/ip/final.txt"
    for line in open(filename,"r"):
        spu = line.strip().split(",")
        checktable[int(spu[0])] = spu[1:]
    return geoBlockList,checktable

#----------------------------------------------------------
# @in: ip地址
# @out: 索引id值
# @function: 将ip地址转化为索引id值
#----------------------------------------------------------
def compute(address):
    if(not address):
        return None
    ipTuple = address.split('.')
    if(len(ipTuple) !=4 ):
        return None
    ( o1, o2, o3, o4 ) = ipTuple
    integer_ip = ( 16777216 * int(o1) ) + ( 65536 * int(o2) ) + ( 256 * int(o3) ) + int(o4)
    return integer_ip

#----------------------------------------------------------
# @out: 组装所有资源
# @function: 返回所有用到资源
#----------------------------------------------------------
def load_resource():
    resource = {"checktable":{},"sorted_spantable":[]}
    resource["sorted_spantable"] , resource["checktable"] = load()
    return resource

#----------------------------------------------------------
# @in: (1)ip地址 (2)资源
# @out: 查询结果
# @function: 查询输入ip地址对应的地理信息
#----------------------------------------------------------
def check_by_ip(ipID,resource):
    if not ipID:
        return None
    index = search2(resource['sorted_spantable'], ipID)
    cityInfo =  resource['checktable'].get(index)
    if cityInfo and len(cityInfo) >=10 :
        result = {"country":cityInfo[0],"region":cityInfo[1],"city":cityInfo[2],"postalCode":cityInfo[3],"latitude":cityInfo[4],"longitude":cityInfo[5],"metroCode":cityInfo[6],"areaCode":cityInfo[7],"countryCode":cityInfo[8],"cityCode":cityInfo[9]}
        return result
    return None

resource = load_resource()
def getCityInfo(ipAddress):
    ipID = compute(ipAddress)
    res = check_by_ip(ipID,resource)
    return res

for line in sys.stdin:
    detail = line.strip().split('\t')
    if (len(detail) < 4):
        continue
    (ip, user_id, unique_id, platform) = detail
    cityInfo = getCityInfo(ip)
    if cityInfo is None :
        print '%s\t%s\t%s\t%s' % ('{}', user_id, unique_id, platform)
    else:
        print '%s\t%s\t%s\t%s' % (cityInfo, user_id, unique_id, platform)
     
if __name__ == '__main__':
    pass